#!/bin/sh

# This script allows one to create new db DOMjudge: domjudge2.
# See usage below for possible commands and options.


set -e

ETCDIR="/usr/local/domjudge/domserver/etc"
PASSWDFILE="$ETCDIR/dbpasswords_db2.secret"
ROLES='teamz juryz publicz pluginz'

# Wrapper around mysql command to allow settings options, user, etc.
#se conecta a msql
mysql()
{
	local user pass
	if [ -n "$DBUSER" ]; then
		user="-u $DBUSER"
	else
		user="${DBA_USER:+-u ${DBA_USER}}"
	fi
	if [ -n "$PASSWD" ]; then
		pass="-p$PASSWD"
	else
		pass=""
		[ -n "$PROMPT_PASSWD" ] && pass="-p"
		[ -n "$DBA_PASSWD" ]    && pass="-p$DBA_PASSWD"
	fi
	command mysql $user $pass -h $DBHOST --silent --skip-column-names "$@"
}


read_dbpasswords()
{
	local OLDIFS 
	OLDIFS="$IFS"
	IFS=":"
	# Don't pipe $PASSWDFILE into this while loop as that spawns a
	# subshell and then variables are not retained in the original shell.
	while read role host db user passwd; do
		# Skip lines beginning with a '#'
		[ "x$role" != "x${role###}" ] && continue
		eval "${role}_DBHOST=$host"
		eval "${role}_DBNAME=$db"
		eval "${role}_DBUSER=$user"

		eval "${role}_PASSWD=$passwd"
		if [ "x$role" = xjuryz ]; then
			DBHOST=$host
			DBNAME="$db"
		fi

	done < "$PASSWDFILE"
	IFS="$OLDIFS"
	##adiciono el caracter z a las siguientes vars porque todos los roles terminan en z
	if [ -z "$juryz_PASSWD" -o -z "$teamz_PASSWD" -o -z "$publicz_PASSWD" ]; then
		echo "Error: no login info found for one of jury, team, public users."
		return 1
	fi
	
}

status()
{
	if [ ! -r "$PASSWDFILE" ]; then
		echo "Error: cannot read database passwords file '$PASSWDFILE'."
		return 1
	fi
	read_dbpasswords || return 1

	echo -n "Trying to connect to the server as DB admin: "
	mysql -e 'SELECT "success.";' || return 1

	for role in $ROLES ; do
		eval "user=\$${role}_DBUSER"
		eval "pass=\$${role}_PASSWD"
		echo -n "Trying to connect to the server with role '$role': "
		DBUSER=$user PASSWD=$pass mysql -e 'SELECT "success.";' || return 1
	done

	echo -n "Searching for database \`$DBNAME\`: "
	mysql -e "USE \`$DBNAME\`; SELECT 'found.';" || return 1

	echo -n "Searching for data in database: "
	DBUSER=$jury_DBUSER PASSWD=$jury_PASSWD \
		mysql -e "USE \`$DBNAME\`; SELECT name FROM team_category WHERE categoryid = '4';" || return 1

	echo -n "MySQL server version: "
	mysql -e 'SELECT version();'
}

create_db_users()
{
	local user pass
	(
	echo "CREATE DATABASE \`$DBNAME\` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;"
	for role in $ROLES ; do
		eval "user=\$${role}_DBUSER"
		eval "pass=\$${role}_PASSWD"
# Need to add both '%' and 'localhost' as entries, because a default
# fresh MySQL installation has a Host='localhost',User='' entry which
# is more specific than Host='%' and thus leads to Access Denied errors.
		echo "CREATE USER
			'$user'@'%' IDENTIFIED BY '$pass',
			'$user'@'localhost' IDENTIFIED BY '$pass';"
	done
	echo "FLUSH PRIVILEGES;"
	) | mysql
}


### Script starts here ###

# Parse command-line options:
while getopts ':u:p:r' OPT ; do
	case "$OPT" in
		u)
			DBA_USER=$OPTARG
			;;
		p)
			DBA_PASSWD=$OPTARG
			;;
		r)
			PROMPT_PASSWD=1
			;;
		:)
			echo "Error: option '$OPTARG' requires an argument."
			exit 1
			;;
		?)
			echo "Error: unknown option '$OPTARG'."
			exit 1
			;;
		*)
			echo "Error: unknown error reading option '$OPT', value '$OPTARG'."
			exit 1
			;;
	esac
done
shift $((OPTIND-1))

case "$1" in

status)
	if status ; then
		echo "Database check successful: database and users present and accessible."
		exit 0
	else
		echo "Database status check failed."
		exit 1
	fi
	;;


install)
### primero creo users y passwd para los usuarios de la db2###
	./dbpasswords > $ETCDIR/dbpasswords_db2.secret
	read_dbpasswords
	create_db_users
	TMPFILE=`mktemp ../tmp/domjudge-sql.XXXXXX`
	cp privilegios_domjudge2.sql $TMPFILE
	for role in $ROLES ; do
		eval "user=\$${role}_DBUSER"
		sed -i -e "s/domjudge_$role/$user/g" $TMPFILE
	done
	cat db_domjudge2_structure.sql \
	    db_domjudge2_example.sql \
	    $TMPFILE | mysql -D "$DBNAME"
	cat $TMPFILE
	rm -f $TMPFILE
	;;


	*)
	cat <<EOF
Unknown subcommand '$1'
Usage: $0 [option]... <command>

Commands:
  status     check database installation status
  install    create database, contents and users if not existing


Options:
  -u <user>  connect to MySQL with DB admin <user>
  -r         read DB admin password from prompt

EOF
	exit 1
	;;

esac
